﻿using Cofe.Core.Filter;
using Cofe.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cofe.Core.Filter
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFE)]
    public class FilterConstructor : IFilterConstructor
    {
        #region Constructor

        #endregion

        #region Methods

        public bool TryConstruct<T>(string name, string value, out T constructedFilter)
            where T : IFilter
        {
            name = name.ToLower();
            constructedFilter = default(T);

            foreach (var ff in FilterFactories)
                if (ff.SupportedFilterTypes.ContainsKey(name))
                {
                    constructedFilter = ff.Construct<T>(name, value);
                    return constructedFilter != null;
                }

            return false;
        }

        public T Construct<T>(string name, string value)
            where T : IFilter
        {
            T constructedFilter;
            if (TryConstruct(name, value, out constructedFilter))
                return constructedFilter;

            else
                throw new NotSupportedException(name);
        }

        #endregion

        #region Data

        IFilterFactory[] _filterFactories = null;

        #endregion

        #region Public Properties

        public IFilterFactory[] FilterFactories
        {
            get { return _filterFactories ?? CofeServices.ServiceLocater.FindAllServices<IFilterFactory>().ToArray(); }
            set { _filterFactories = value; }
        }

        #endregion
    }
}
